// DOM元素引用
const fileInput = document.getElementById('fileInput');
const fileLabel = document.getElementById('fileLabel');
const uploadBtn = document.getElementById('uploadBtn');
const progressBar = document.getElementById('progressBar');
const progressText = document.getElementById('progressText');
const statusEl = document.getElementById('status');

// 当前选中的文件
let currentFile = null;

// 初始化事件监听
function initEventListeners() {
	// 文件选择变化
	fileInput.addEventListener('change', handleFileSelect);

	// 上传按钮点击
	uploadBtn.addEventListener('click', uploadFile);

	// 拖放功能支持
	setupDragAndDrop();
}

// 处理文件选择
function handleFileSelect(e) {
	if (e.target.files.length > 0) {
		currentFile = e.target.files[0];
		fileLabel.textContent = currentFile.name;
		updateStatus(`已选择: ${currentFile.name} (${formatFileSize(currentFile.size)})`, 'status-default');
		resetProgress();
	}
}

// 设置拖放功能
function setupDragAndDrop() {
	const dropArea = document.querySelector('.upload-area');

	// 防止默认拖放行为
	['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
		dropArea.addEventListener(eventName, preventDefaults, false);
	});

	// 高亮拖放区域
	['dragenter', 'dragover'].forEach(eventName => {
		dropArea.addEventListener(eventName, highlight, false);
	});

	['dragleave', 'drop'].forEach(eventName => {
		dropArea.addEventListener(eventName, unhighlight, false);
	});

	// 处理文件拖放
	dropArea.addEventListener('drop', handleDrop, false);
}

function preventDefaults(e) {
	e.preventDefault();
	e.stopPropagation();
}

function highlight() {
	document.querySelector('.file-input-label').style.backgroundColor = '#e0f7fa';
}

function unhighlight() {
	document.querySelector('.file-input-label').style.backgroundColor = '';
}

function handleDrop(e) {
	const dt = e.dataTransfer;
	if (dt.files.length) {
		fileInput.files = dt.files;
		handleFileSelect({ target: fileInput });
	}
}

// 上传文件
function uploadFile() {
	if (!currentFile) {
		updateStatus('请先选择文件', 'error');
		return;
	}

	// 禁用按钮防止重复上传
	uploadBtn.disabled = true;
	updateStatus('上传中...', 'status-default');

	const xhr = new XMLHttpRequest();
	const formData = new FormData();
	formData.append('file', currentFile);

	// 进度监听
	xhr.upload.addEventListener('progress', function (e) {
		if (e.lengthComputable) {
			const percent = Math.round((e.loaded / e.total) * 100);
			updateProgress(percent);
		}
	});

	// 请求完成
	xhr.addEventListener('load', function () {
		uploadBtn.disabled = false;

		try {
			const response = JSON.parse(xhr.responseText);
			if (response.success) {
				console.log(response);
				updateStatus(response.message, 'success');
			} else {
				updateStatus(`上传失败: ${response.detail || '未知错误'}`, 'error');
			}
		} catch (error) {
			updateStatus('上传失败: 服务器响应异常', 'error');
		}
	});

	// 错误处理
	xhr.addEventListener('error', function () {
		uploadBtn.disabled = false;
		updateStatus('网络错误: 上传失败', 'error');
	});

	// 发送请求
	xhr.open('POST', '/upload', true);
	xhr.send(formData);
}

// 更新进度显示
function updateProgress(percent) {
	progressBar.value = percent;
	progressText.textContent = `${percent}%`;
}

// 重置进度
function resetProgress() {
	progressBar.value = 0;
	progressText.textContent = '0%';
}

// 更新状态消息
function updateStatus(message, className) {
	statusEl.textContent = message;
	statusEl.className = className;
}

// 格式化文件大小
function formatFileSize(bytes) {
	if (bytes === 0) return '0 Bytes';
	const k = 1024;
	const sizes = ['Bytes', 'KB', 'MB', 'GB'];
	const i = Math.floor(Math.log(bytes) / Math.log(k));
	return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 初始化应用
document.addEventListener('DOMContentLoaded', initEventListeners);